package com.dc.boot.autoconfigure.swagger2;

import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.ChildBeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.swagger2.annotations.EnableSwagger2;


/*******************************************************************************
 * 文件名: Swagger2GroupAutoConfiguration.java.java <br>
 * 版本: <br>
 * 描述: 所属地配置 控制器  <br>
 * 版权所有:神州数码<br>
 * //////////////////////////////////////////////////////// <br>
 * 创建者: 王建栋 <br>
 * 创建日期: 2017年8月4日 <br>
 * 修改者: <br>
 * 修改日期: <br>
 * 修改说明: <br>
 ******************************************************************************/
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Swagger2GroupProperties.class)
@ConditionalOnProperty(prefix = "spring.swagger2Group", name = "enabled", matchIfMissing = false)
public class Swagger2GroupAutoConfiguration {

	private static final String docketFactory="docketFactory";
	private static final String SUFFIX="_swagger2Api";
	@Autowired
	private Swagger2GroupProperties swagger2GroupProperties;
	
	@Autowired
    private ApplicationContext app;
	
	@Bean
	public DocketFactory docketFactory(){
		return new DocketFactory();
	}
	
	
	@Bean
	public String swagger2Api(){
		
		DefaultListableBeanFactory acf = (DefaultListableBeanFactory) app.getAutowireCapableBeanFactory();  
        BeanDefinition beanDefinition;  
        for(Entry<String, Swagger2Properties> entry:swagger2GroupProperties.getGroup().entrySet()){
        	
        	//application的id中包含冒号的时候，会报错，在这里，先去掉
			String appliation=app.getId();
			if(appliation.indexOf(":")!=-1){
				appliation=appliation.substring(0,appliation.indexOf(":"));
			}
			beanDefinition = new ChildBeanDefinition(appliation);  
			beanDefinition.setFactoryBeanName(docketFactory);
			beanDefinition.setFactoryMethodName("getDocket");
			DocketFactory factory=(DocketFactory)acf.getBean(docketFactory);
			factory.setGroupName(entry.getKey());
			factory.setSwagger2GroupProperties(swagger2GroupProperties);
			factory.setSwagger2Properties(entry.getValue());
			
			acf.registerBeanDefinition(generyKey(entry.getKey()), beanDefinition);  
			acf.getBean(generyKey(entry.getKey()));
        }
		return null;
	}
	
	private String generyKey(String key){
		return key+SUFFIX;
	}
	
	
}

